﻿var gameLobby = function () {
    var user = "User" + Math.round(Math.random() * 10000);
    var host = "ws://xa-lw-liu1:8000"
    var socket;
    var currentRoom;
    var currentMessageBox;
    var gamePanel;
    var userGames = {};

    var request = {
        command: "RL",//RL--ROOM LIST,UL--USER LIST,ER--ENTER ROOM,QR--QUIT ROOM,Q--QUIT GAME,PM--PUSH MESSAGE,PMU--PUSH MESSAGE TO USER,WL--WELCOME,CR--CREATE ROOM,SG--START GAME,GM--GET ROOM
        user: "user name",
        data: ""
    };

    function verifyUser(userName) {

    }

    function updateUserList(users) {
        var html = "";
        for (var i = 0; i < users.length; i++) {
            html += "<li>" + users[i].name + "</li>";
        }

        $("#user-list-container ul").html(html);
    }

    function updateRoomList(rooms) {
        var tmpRoom;
        var roomContainer = $("#room-container");

        //remove all rooms
        roomContainer.html("");
        roomList = [];
        for (var i = 0; i < rooms.length; i++) {
            tmpRoom = createRoom(rooms[i]);
            roomList.push(tmpRoom);
            roomContainer.append(tmpRoom);
        }
    }

    function createRoom(room) {
        var html = "";
        html += '<div class="room" data-room-name="' + room.name + '">' +
                  '<div class="caption">' +
                      '<span class="name">' + room.name + '</span>' +
                      '<span class="member-count">Allowed Member Count:' + room.number + '</span>' +
                  '</div>' +
                  '<div class="body">';
        for (var j = 0; j < room.members.length; j++) {
            html += '<div class="member">' +
                           '<img src="portrait.gif" />' +
                           '<div>' + room.members[j] + '</div>' +
                    '</div>';
        }

        html += '</div>' +
                '<div class="footer">' +
                    '<button class="join-button">join</button>' +
                '</div>' +
            '</div>';

        return $(html);
    }

    function addNewRoom(room) {
        var roomEl = createRoom(room);
        $("#room-container").append(roomEl);

        if (room.owner == user) {
            currentRoom = roomEl;
            roomEl.find(".join-button").text("start");
            insertChatContainer(roomEl);
        }
    }

    function pushMessage(sender, message) {
        if (currentMessageBox) {
            currentMessageBox.append("<p><span class=\"message-user\">[" + sender + "]:</span>" + message + "</p>");
            currentMessageBox.scrollTop(currentMessageBox.scrollTop() + currentMessageBox.find("p:last-child").outerHeight(true));
        }
    }

    function insertChatContainer(room) {
        var html = '<div class="chat-container" style="display:none">' +
                        '<div class="message-box"></div>' +
                        '<div class="input-container">' +
                            '<input type="text" class="input-box"/>' +
                            '<button class="send-button">send</button>' +
                        '</div>' +
                    '</div>';
        var chatContainer = $(html);
        currentMessageBox = chatContainer.find(".message-box");
        if (room) {
            chatContainer.insertBefore(room.find(".footer"));
            chatContainer.show("slow");
        }

        return chatContainer;

    }

    function getRoom(roomName) {
        return $("#room-container [data-room-name=\"" + roomName + "\"]");
    }

    function removeRoom(roomName) {
        var room = getRoom(roomName);
        if (room) {
            var index = rooms.indexOf(room);
            room.detach();
            rooms.splice(index, 1);
        }
    }

    function enterRoom(enteredUser, roomName) {
        var room = getRoom(roomName);
        if (room) {
            room.find(".body").append('<div class="member" data-user-name="' + enteredUser + '">' +
                                            '<img src="portrait.gif" />' +
                                            '<div>' + enteredUser + '</div>' +
                                       '</div>');

            if (enteredUser == user) {
                insertChatContainer(room);
                room.find(".join-button").text("quit");
            }
        }
    }

    function quitRoom(quitUser, roomName) {
        var room = getRoom(roomName);
        if (room) {
            room.find("[data-user-name=\"" + quitUser + "\"]").detach();

            if (quitUser == user) {
                room.find(".chat-container").detach();
                room.find(".join-button").text("join");
            }
        }
    }

    function startGame(room) {
        gamePanel.css("display", "block");
        var userGameIndex=1;
        for (var i = 0; i < room.members.length; i++) {
            if (room.members[i] == user) {
                userGames[room.members[i]] = buildUserGame("self-box", room.members[i],socket ,true);
            } else {
                userGames[room.members[i]] = buildUserGame("user-game-" + userGameIndex, room.members[i],socket, false);
                userGameIndex++;
            }
        }

        userGames[user].start();
    }

    return {
        init: function () {
            $("#login-container").text(user);
            gamePanel = $("#game-panel");

            $("#login-container").click(function () {
                user = prompt("Please input the user name that want to use.", user);
                if (!user) {
                    alert("Use Name can not be empty!");
                } else {
                    $("#login-container").text(user);
                }
            });

            $("#connect").click(function () {
                if ($("#connect").text() == "CONNECT") {
                    socket = new WebSocket(host + "/" + user, "echo-protocol");
                    socket.onmessage = function (event) {
                        console.log(event.data);
                        var dataPackage = JSON.parse(event.data);
                        switch (dataPackage.command) {
                            case "UL":
                                updateUserList(dataPackage.data);
                                console.log("receive UL command");
                                break;
                            case "WL":
                                console.log("receive WL command");
                                if (dataPackage.user == user) {
                                    $("#connect").text("DISCONNECT")
                                    socket.send("{\"command\":\"RL\"}");
                                }
                                socket.send("{\"command\":\"UL\"}");
                                break;
                            case "RL":
                                updateRoomList(dataPackage.data);
                                console.log("receive RL command");
                                break;
                            case "CR":
                                if (dataPackage.code == 200) {
                                    addNewRoom(dataPackage.data);
                                } else {
                                    alert(dataPackage.message);
                                }
                                break;
                            case "PM":
                                pushMessage(dataPackage.user, dataPackage.data);
                                break;
                            case "ER":
                                if (dataPackage.code == 200) {
                                    enterRoom(dataPackage.user, dataPackage.data);
                                }
                                break;
                            case "QR":
                                quitRoom(dataPackage.user, dataPackage.data);
                                break;
                            case "RM":
                                break;
                            case "SG":
                                startGame(dataPackage.data);
                                break;
                                //case "Q":
                                //    if (dataPackage.user = user) {
                                //        $("#connect").text("");
                                //        $("#user-list-container ul").html("");
                                //        $("#room-container").html("");
                                //    }
                                //    break;
                            case "GA":
                                if (dataPackage.user != user) {
                                    userGames[dataPackage.user].processCommand(dataPackage);
                                }
                                break;
                        }
                    };

                    socket.onerror = function (event) {
                        console.log(event);
                    };
                } else {
                    if (socket) {
                        socket.send("{\"command\":\"Q\"}");
                        socket.close();
                    }
                }
            });

            $("#create-room").click(function () {
                var newRoomName = prompt("Please input the new room name.");
                if (!newRoomName) {
                    alert("Invalid room name!");
                } else {
                    if (socket) {
                        socket.send(JSON.stringify({ command: "CR", "data": newRoomName }));
                    }
                }
            });

            $("#room-container").on("click", "button.send-button", function (event) {
                var room = $(this).parents(".room");
                if (room) {
                    var text = room.find(".input-box").val();
                    if (text) {
                        var roomName = room.attr("data-room-name");
                        if (socket) {
                            socket.send(JSON.stringify({ command: "PM", data: text }));
                            room.find(".input-box").val("");
                        } else {
                            alert("The connection is disconnected.Please re-connect!");
                        }
                    }
                }
            });

            $("#room-container").on("click", "button.join-button", function (event) {
                var room = $(this).parents(".room");
                if (room) {
                    var roomName = room.attr("data-room-name");
                    if ($(this).text() == "join") {
                        if (socket) {
                            socket.send(JSON.stringify({ command: "ER", data: roomName }));
                        }
                    } else if ($(this).text() == "quit") {
                        if (socket) {
                            socket.send(JSON.stringify({ command: "QR", data: roomName }));
                        }
                    } else if ($(this).text() == "start") {
                        if (socket) {
                            socket.send(JSON.stringify({ command: "SG", data: roomName }));
                        }
                    }
                }
            });

            $("#room-container").on("keydown", "input.input-box", function (event) {
                if (event.keyCode == 13) {
                    var room = $(this).parents(".room");
                    if (room) {
                        var text = room.find(".input-box").val();
                        if (text) {
                            var roomName = room.attr("data-room-name");
                            if (socket) {
                                socket.send(JSON.stringify({ command: "PM", data: text }));
                                room.find(".input-box").val("");
                            } else {
                                alert("The connection is disconnected.Please re-connect!");
                            }
                        }
                    }
                }
            });

            $("#quit-game-panel").click(function () {
                gamePanel.css("display", "none");
            });
        }
    };
}();

$(function () {
    gameLobby.init();
});